package com.dylan.历史.跟书.effectivejava.item02构建器;

/**
 * @author : ankang
 * @date : 2019/5/26 21:18
 * @Description : 构建器模式
 * 1. 当参数较多，而且有可选参数时可使用构建器模式
 * 2. 可以生成不可变对象（没有set方法）
 * 3. 安全，在设置全部所需参数后才创建对象
 */
public class NutritionFacts {
    private int servingSize;
    private int servings;
    private int calories;
    private int fat;
    private int sodium;
    private int carbohydrate;

    private NutritionFacts(Builder builder) {
        this.servingSize = builder.servingSize;;
        this.servings = builder.servings;;
        this.calories = builder.calories;;
        this.fat = builder.fat;;
        this.sodium = builder.sodium;;
        this.carbohydrate = builder.carbohydrate;;
    }

    public static class Builder {
        // 必须的参数
        private int servingSize;
        private int servings;
        // 可选参数
        private int calories;
        private int fat;
        private int sodium;
        private int carbohydrate;

        public Builder(int servingSize, int servings) {
            this.servingSize = servingSize;
            this.servings = servings;
        }

        public Builder calories(int calories) {
            this.calories = calories;
            return this;
        }

        public Builder fat(int fat) {
            this.fat = fat;
            return this;
        }

        public Builder sodium(int sodium) {
            this.sodium = sodium;
            return this;
        }

        public Builder carbohydrate(int carbohydrate) {
            this.carbohydrate = carbohydrate;
            return this;
        }

        public NutritionFacts build() {
            return new NutritionFacts(this);
        }
    }

    public int getServingSize() {
        return servingSize;
    }

    public int getServings() {
        return servings;
    }

    public int getCalories() {
        return calories;
    }

    public int getFat() {
        return fat;
    }

    public int getSodium() {
        return sodium;
    }

    public int getCarbohydrate() {
        return carbohydrate;
    }
}
